package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.model.QrCodeDebitFeeRateData;
import com.cardbaobao.cardbabyclient.model.QrCodeDebitOrder;
import com.cardbaobao.cardbabyclient.model.result.QrCodeDebitOrderResult;
import com.cardbaobao.cardbabyclient.model.result.TransactionDataResult;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.ChooseDebitChannelAdapter;
import com.cardbaobao.cardbabyclient.ui.helper.QrCodeHelper;
import com.cardbaobao.cardbabyclient.ui.pop.ListPop;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.utils.FileUtils;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ScreenUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnLongClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Jiangzx on 2017/9/11 19:58.
 */

public class QrCodeDebitShowActivity extends BaseActivity {
    public static final String QR_CODE_CONTENT_S = "qrCodeContent";

    public static final String QR_CODE_DEBIT_ORDER_NUMBER_S="qrCodeOrderNumber";

    @BindView(R.id.title_bar)
    TitleBar titleBar;


    @BindView(R.id.ll_container)
    LinearLayout llContainer;
    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.iv_qr_code)
    ImageView ivQrCode;
    @BindView(R.id.iv_qr_code_channel)
    ImageView ivQrCodeChannel;
    @BindView(R.id.tv_qr_code_channel)
    TextView tvQrCodeChannel;

    @BindView(R.id.tv_scan_code_des)
    TextView tvScanCodeDes;

    private int qrCodeSize;

    private String orderNumber;
    private String qrCodeContent;
    private String amount;
    private String fee;
    private String arrival;
    private QrCodeDebitFeeRateData.FeeRate rate;
    private ArrayList<QrCodeDebitFeeRateData.FeeRate> rates;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_qr_code_debit_show;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        this.qrCodeSize = DensityUtil.dp2px(180);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        Intent intent = getIntent();

        mCurrentPageId= Self.Page.app_qrcode_receivables;

        amount = intent.getStringExtra(QrCodeDebitActivity.DEBIT_AMOUNT_S);
        fee = intent.getStringExtra(QrCodeDebitActivity.DEBIT_FEE_S);
        arrival = intent.getStringExtra(QrCodeDebitActivity.DEBIT_ARRIVAL_S);
        rate = intent.getParcelableExtra(QrCodeDebitActivity.DEBIT_RATE_O);
        rates = intent.getParcelableArrayListExtra(FeeRateActivity.QR_CODE_DEBIT_FEE_RATE_LIST_ARRAY);
        qrCodeContent = intent.getStringExtra(QR_CODE_CONTENT_S);
        orderNumber=intent.getStringExtra(QR_CODE_DEBIT_ORDER_NUMBER_S);
        tvAmount.setText(
                "￥"+
                (String.format(Locale.CHINESE,Constant.AMOUNT_FORMAT,Double.parseDouble(amount)))
        );
        setDebitShowUi(rate);
        setQrCode(qrCodeContent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        GoogleAnalyticsUtil.setScreenName("二维码收款-展示二维码");
    }

    private void setDebitShowUi(QrCodeDebitFeeRateData.FeeRate rate){
        String channelName="";
        switch (rate.getChannel_type()){
            case Constant.KQB010102:
                channelName="微信";
                break;
            case Constant.KQB010103:
                channelName="支付宝";
                break;
            case Constant.KQB010104:
                channelName="京东";
                break;
            case Constant.KQB010105:
                channelName="QQ";
                break;
        }
        titleBar.setTitleText(channelName + "收款");
        ImageLoaderUtil.displayImageWithPlaceHolder(URLUtil.CBB_IMG_URL + rate.getPicture_path(),
                ivQrCodeChannel,
                R.mipmap.img_default_square);
        tvQrCodeChannel.setText(channelName);
        tvScanCodeDes.setText("将二维码保存或者打印，\n使用"+channelName+"扫码收款，支持信用卡");
    }

    @OnClick({R.id.ll_change_qr_code_channel,R.id.bt_query_result})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_change_qr_code_channel:
                showChooseChannelPop();
                break;
            case R.id.bt_query_result:
                if(!TextUtils.isEmpty(orderNumber)){
                    queryQrCodeDebitResult(orderNumber);
                }
                break;
        }
    }

    @OnLongClick({R.id.iv_qr_code})
    public boolean onQrCodeLongClick(View view){
        if(view.getId()==R.id.iv_qr_code){
            //弹出保存二维码对话框
            if(!TextUtils.isEmpty(qrCodeContent)){
                showQrCodeSaveDialog();
            }
            return true;
        }
        return false;
    }

    private void showQrCodeSaveDialog(){
        new AlertDialog.Builder(mContext).
                setTitle("温馨提示").
                setMessage("要将二维码保存到手机吗？").
                setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        saveQrCode();
                    }
                }).show();
    }

    //保存二维码
    private void saveQrCode(){
        showProgressDialog(false);
        Observable.OnSubscribe<String> observable=new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                File file= FileUtils.getFile(FileUtils.QR_CODE_SAVE_PATH,
                        new SimpleDateFormat("yyyyMMddHHmmssSSS",Locale.CHINESE).format(System.currentTimeMillis())+".jpg");
                if(file!=null){
                    llContainer.setDrawingCacheEnabled(true);
                    int width=llContainer.getWidth();
                    int height=llContainer.getHeight();
                    //argb8888
                    int size= (int) (width*height*4*getResources().getDisplayMetrics().density);
                    llContainer.setPersistentDrawingCache(size);
                    llContainer.buildDrawingCache();
                    Bitmap bitmap=llContainer.getDrawingCache();
                    if(bitmap!=null){
                        BufferedOutputStream bos=null;
                        try{
                            bos=new BufferedOutputStream(new FileOutputStream(file),4*1024);
                            if(bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos)){
                                //二维码保存成功
                                subscriber.onNext(file.getAbsolutePath());
                            }else{
                                //保存失败
                                subscriber.onNext(null);
                            }
                            subscriber.onCompleted();
                        }catch (Exception e){
                            e.printStackTrace();
                            subscriber.onError(e);
                        }finally {
                            if(bos!=null){
                                try {
                                    bos.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }else{
                    subscriber.onError(new RuntimeException("创建文件失败"));
                }
            }
        };
        Observable.unsafeCreate(observable).
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissProgressDialog();
                        ToastUtil.showToast("保存二维码出错");
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        if(TextUtils.isEmpty(s)){
                            ToastUtil.showToast("保存二维码失败");
                        }else{
                            try{
                                File file=new File(s);
                                //将二维码插入图库
                                MediaStore.Images.Media.insertImage(getContentResolver(),
                                        s,
                                        file.getName(),
                                        null);
                                //发送广播，通知图库更新
                                Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                        Uri.fromFile(file));
                                sendBroadcast(intent);
                                ToastUtil.showToast("保存成功");
                            }catch (FileNotFoundException e){
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    //设置二维码
    private void setQrCode(final String content) {
        Observable.OnSubscribe<Bitmap> observable =
                new Observable.OnSubscribe<Bitmap>() {
                    @Override
                    public void call(Subscriber<? super Bitmap> subscriber) {
                        Bitmap bitmap = QrCodeHelper.generateQrCode(content, qrCodeSize, qrCodeSize);
                        if (bitmap != null) {
                            subscriber.onNext(bitmap);
                            subscriber.onCompleted();
                        } else {
                            subscriber.onError(new RuntimeException("生成二维码出错"));
                        }
                    }
                };
        Observable.unsafeCreate(observable).
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Subscriber<Bitmap>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        ToastUtil.showToast(throwable.getMessage());
                        ivQrCode.setImageResource(R.color.transparent);
                    }

                    @Override
                    public void onNext(Bitmap bitmap) {
                        ivQrCode.setImageBitmap(bitmap);
                    }
                });
    }

    private ListPop chooseChannelPop;
    private ChooseDebitChannelAdapter adapter;
    private AdapterView.OnItemClickListener listener;
    private void showChooseChannelPop() {
        Context context = QrCodeDebitShowActivity.this;
        if(adapter==null){
            adapter = new ChooseDebitChannelAdapter(context, rates, Double.parseDouble(amount));
        }
        if(listener==null){
            listener = new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (adapter.canSelect(position)) {
                        chooseChannelPop.dismiss();
                        if (position != adapter.getSelected()) {
                            //切换收款渠道
                            qrCodeDebitOrder(rates.get(position));
                        }
                    }
                }
            };
        }
        for (int i = 0, size = rates.size(); i < size; i++) {
            if (rate.getChannel_type().equals( rates.get(i).getChannel_type())) {
                adapter.setSelected(i);
                break;
            }
        }
        if(chooseChannelPop==null){
            chooseChannelPop = new ListPop(context) {
                @Override
                public void configListView(ListView listView) {
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(listener);
                }
            };
            chooseChannelPop.setTitle("请选择收款渠道");
        }
        if (!chooseChannelPop.isShowing()) {
            chooseChannelPop.showAtLocation(titleBar, Gravity.NO_GRAVITY, 0, 0);
        }
    }


    private void qrCodeDebitOrder(final QrCodeDebitFeeRateData.FeeRate rate) {
        showProgressDialog(false);
        Api.qrCodeDebitOrder(String.valueOf(mApplication.getUser().getID()),
                amount,
                rate.getChannel_type(),
                fee,
                arrival).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_server_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        QrCodeDebitOrderResult result = JsonUtil.json2Object(s, QrCodeDebitOrderResult.class);
                        if (result.getCode() == Constant.SUC_CODE) {
                            QrCodeDebitOrder order = result.getData();
                            if (order != null) {
                                orderNumber=order.getOther_orderNo();
                                qrCodeContent = order.getOther_qRcodeURL();
                                //生成二维码
                                setQrCode(qrCodeContent);
                                QrCodeDebitShowActivity.this.rate=rate;
                                setDebitShowUi(rate);
                            }
                        } else {
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }

    //查看二维码收款结果
    private void queryQrCodeDebitResult(String orderNumber){
        showProgressDialog(false);
        Api.getTransactionDetail(String.valueOf(mApplication.getUser().getID()), orderNumber).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.
                                getApplicationContext().
                                getString(R.string.string_request_server_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        TransactionDataResult result=
                                JsonUtil.json2Object(s,TransactionDataResult.class);
                        if(result.getCode()==Constant.SUC_CODE){
                            String state=result.getData().getTransaction_details().getState();
                            showCodeDebitStatus(state);
                        }else{
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }

    private void showCodeDebitStatus(String state){
        final PopupWindow pop=new PopupWindow(mContext);
        pop.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        pop.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        pop.setClippingEnabled(false);
        final int screenWidth= ScreenUtil.getScreenWidth();
        if("3".equals(state)){
            View contentView= LayoutInflater.
                            from(mContext).
                            inflate(R.layout.pop_qr_code_debit_un_paid,null);
            View container=contentView.findViewById(R.id.ll_container);
            ViewGroup.LayoutParams params=container.getLayoutParams();
            if(params!=null){
                params.width=screenWidth;
                params.height= (int) (screenWidth*463/720.0f);
                container.setLayoutParams(params);
            }
            contentView.findViewById(R.id.bt_ensure).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop.dismiss();
                }
            });
            pop.setContentView(contentView);
        }else{
            View contentView=LayoutInflater.
                    from(mContext).
                    inflate(R.layout.pop_qr_code_debit_already_paid,null);
            if("2".equals(state)){
                contentView.findViewById(R.id.rl_paid_result).
                        setBackgroundResource(R.mipmap.img_pop_pay_failure);
            }
            View container=contentView.findViewById(R.id.rl_paid_result);
            ViewGroup.LayoutParams params=container.getLayoutParams();
            if(params!=null){
                int width= (int) (screenWidth*0.98f);
                params.width=width;
                params.height= (int) (width*528/706.0f);
                container.setLayoutParams(params);
            }
            contentView.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop.dismiss();
                }
            });
            contentView.findViewById(R.id.bt_view_detail).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop.dismiss();
                    Intent intent=new Intent(mContext,TransactionDetailActivity.class);
                    intent.putExtra(TransactionDetailActivity.DETAIL_TYPE_I,
                            TransactionDetailActivity.TYPE_DEBIT);
                    intent.putExtra(TransactionDetailActivity.ORDER_NUMBER_S,
                            orderNumber);
                    intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    startActivity(intent);
                }
            });
            pop.setContentView(contentView);
        }
        pop.setBackgroundDrawable(new ColorDrawable());
        pop.showAtLocation(titleBar,Gravity.NO_GRAVITY,0,0);
    }
}
